package com.xiaobaibai.config;

import com.alibaba.fastjson.JSON;
import com.xiaobaibai.common.response.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Map;

public class MyInterceptor implements HandlerInterceptor {

//    @Autowired
//    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //记住  既然这里读取了Body里面的内容,
        //那么在形参里就不要定义@RequestBody了,因为这个body只能读一次,定义了这里会报错
        /**
         * 0.最优的解决方案,我在security的拦截器中读取了之后就把它setAttribute存起来,
         *   然后controller层不要用@RequestBody取,直接在方法体中用request.getAttribute取
         * 1.先看在securityFilter中set.request行不行
         * 2.不行再到时候就在最外面加一个原生Filter
         */

        BufferedReader br = request.getReader();
        String str = "";
        String data = "";
        while ((str = br.readLine()) != null) {
            data += str;
        }
        Map<String,String> filterLoginData = JSON.parseObject(data, Map.class);
        request.setAttribute("loginData",filterLoginData);




        System.out.println(request.getRequestURL());

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
